﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.Infrastructure
{
    /// <summary>
    /// 调用Restful服务，封装了HttpClient的基本方法
    /// </summary>
    public class nbHttpClient
    {
        /// <summary>
        /// 以Post方式来同步请求Web Api接口
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="dicParams">请求参数</param>
        /// <returns></returns>
        public static string Post(string url, IDictionary<string, string> dicParams = null)
        {
            // 请求参数集合
            var paramList = new List<KeyValuePair<String, String>>();
            if (dicParams != null)
            {
                foreach (var p in dicParams)
                {
                    paramList.Add(new KeyValuePair<string, string>(p.Key, p.Value));
                }
            }

            // 发起异步Post请求
            var httpClient = new HttpClient();
            var response = httpClient.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList)).Result;
            var result = response.Content.ReadAsStringAsync().Result;

            //#region 插入日志表
            //var RequestInfo = JsonConvert.SerializeObject(new { URL = url, Params = paramList });
            //#endregion

            return result;
        }

        /// <summary>
        /// 以Post方式来异步请求
        /// </summary>
        /// <param name="requestXml"></param>
        /// <returns></returns>
        public static async Task<string> PostAsync(string url, IDictionary<string, string> dicParams = null)
        {
            // 请求参数集合
            var paramList = new List<KeyValuePair<String, String>>();
            if (dicParams != null)
            {
                foreach (var p in dicParams)
                {
                    paramList.Add(new KeyValuePair<string, string>(p.Key, p.Value));
                }
            }

            // 发起异步Post请求
            var httpClient = new HttpClient();
            var response = await httpClient.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList));
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 以Get方式来异步请求Web Api接口
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public static string GetAsync(string url)
        {
            // 发起异步Get请求
            var httpClient = new HttpClient();
            var response = httpClient.GetAsync(url).Result;
            var result = response.Content.ReadAsStringAsync().Result;

            //#region 插入日志表
            //var RequestInfo = JsonConvert.SerializeObject(new { URL = url });
            //#endregion

            return result;
        }
    }
}
